package cn.trda.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.trda.mapper.AsUserMapper;
import cn.trda.pojo.Role;
import cn.trda.pojo.User;
import cn.trda.pojo.UserExt;
import cn.trda.service.RoleService;
import cn.trda.service.Userservice;
import cn.trda.util.MD5Util;
import cn.trda.util.MySqlPageUtil;
@Controller
@RequestMapping("user")
public class UserConteoller extends BaseController{
	private static final Logger logger = Logger.getLogger(UserConteoller.class);
	@Autowired
	private AsUserMapper asUserMapper;
	@Autowired
	private RoleService roleService;
	@Autowired
	private Userservice userservice;
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String main(User asuser,BindingResult result,Model model,HttpSession session ) {
		if(result.hasErrors()){
			List<ObjectError> errors = result.getAllErrors();
			model.addAttribute("errors", errors);
			return "login";
		}else{
			asuser.setUserpassword(MD5Util.encode(asuser.getUserpassword()));
			User user =asUserMapper.selectByUser(asuser);
			if(user==null){
				model.addAttribute("login_error", "用户名或者密码错误");
				return "login";
			}else{
				session.setAttribute("user", user);
				if (logger.isDebugEnabled()) {
					logger.debug(user);
				}
				return "main";
			}
		}
		
	}
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		// 清除用户
		session.removeAttribute("user");
		return "redirect:login";
	}
	@RequestMapping(value = "/password/update", method = RequestMethod.GET)
	public String updatepassword() {
		// 清除用户
		
		return "update_password";
	}
	@RequestMapping(value = "/password/check", method = RequestMethod.POST)
	@ResponseBody
	public  String checkpassword(String oldpassword,HttpSession session) {
		User user = this.getSessionUser(session);
		logger.debug(user.getUserpassword());
		logger.debug(MD5Util.encode(oldpassword));
		
		if (user.getUserpassword().equals(MD5Util.encode(oldpassword))) {
			return "success";
		}
		return "fail";
	}
	@RequestMapping(value = "password/update", method = RequestMethod.POST)
	@ResponseBody
	public  String dopassword(String newpassword,HttpSession session) throws Exception {
		User user = this.getSessionUser(session);
		user.setUserpassword(MD5Util.encode(newpassword));
		user.setLastupdatetime(new Date());
		//System.out.println(user);
		if (asUserMapper.updateByPrimaryKey(user)==1) {
			return "success";
		}
		return "fail";
	}
	@RequestMapping( "/manage")
	public String manage(Model model) throws Exception {
	
		List<Role> roles = roleService.selectAll(1);
		model.addAttribute("roles", roles);
		
		return "user_manage";
	}
	@RequestMapping("/list")
	@ResponseBody
	private Map getlist(User user, Integer page, Integer rows){
		UserExt ue=new UserExt();
		ue.setUser(user);
		MySqlPageUtil mp=new MySqlPageUtil(page, rows);
		ue.setPage(mp);
		Map<String,Object> map=new HashMap<String, Object>();
		//System.out.println(userservice.getPagedCount(ue));
		map.put("total", userservice.getPagedCount(ue));
		map.put("rows", userservice.getPagedUsers(ue));
		
		return map;
	}
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String updateUser(@PathVariable Long id, Model model){
	
		List<Role> roles = roleService.selectAll(1);
		model.addAttribute("roles", roles);
		User user=userservice.selectByPrimaryKey(id);
		
		model.addAttribute("user", user);
		return "user_update";
	}
	@RequestMapping(value="/update",method = RequestMethod.POST)
	@ResponseBody
	public String updateUserS(User user){
	user.setCreationtime(new Date());
	//System.out.println(userservice.updateByPrimaryKeySelective(user));
		if(userservice.updateByPrimaryKeySelective(user)==1){
			return "success";
		}
		return "fail";
	}
	@RequestMapping(value="/add",method=RequestMethod.GET)
	private String toadd(Model model){
		List<Role> roles = roleService.selectAll(1);
		model.addAttribute("roles", roles);
		return "user_add";
	}
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	private String add(User user,HttpSession session){
		user.setCreationtime(new Date());
		user.setCreatedby(this.getSessionUser(session).getCreatedby());
		if(userservice.insertSelective(user)==1){
			return "success";
		}
		return "fail";
	}
	@RequestMapping(value = "check", method = RequestMethod.POST)
	@ResponseBody
	public  String checkUsercode(String usercode) throws Exception {
		User user = new User();
		user.setUsercode(usercode);
		if (userservice.selectByUser(user) == null) {
			return "success";
		} else {
			return "fail";
		}
	}
	@RequestMapping(value="/delete",method=RequestMethod.GET)
	@ResponseBody
	private String deleteUser(Long id){
		if(userservice.deleteByPrimaryKey(id)==1){
			return "success";
		}
		return "fail";
	}
}
